<template>
  <span>
    {{ displayedText }}
    <span v-if="isTyping" class="typing-cursor">|</span>
  </span>
</template>

<script>
export default {
  props: {
    text: String,
    startPosition: {
      type: Number,
      default: 0
    },
    isStreaming: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      displayedText: '',
      currentPos: this.startPosition,
      isTyping: false,
      typingInterval: null
    }
  },
  watch: {
    text(newVal) {
      if (this.isStreaming) {
        this.startTyping(newVal);
      } else {
        // 非流式状态直接显示全部内容
        this.displayedText = newVal;
      }
    },
    isStreaming(newVal) {
      if (!newVal) {
        this.displayedText = this.text;
        this.clear();
      }
    }
  },
  methods: {
    startTyping(fullText) {
      this.clear();
      this.isTyping = true;

      // 从startPosition开始显示
      this.typingInterval = setInterval(() => {
        if (this.currentPos < fullText.length) {
          this.displayedText = fullText.substring(0, this.currentPos + 1);
          this.currentPos++;
        } else {
          this.clear();
          this.$emit('complete');
        }
      }, 30);
    },
    clear() {
      if (this.typingInterval) {
        clearInterval(this.typingInterval);
        this.typingInterval = null;
        this.isTyping = false;
      }
    }
  },
  mounted() {
    this.startTyping(this.text);
  },
  beforeUnmount() {
    this.clear();
  }
}
</script>